package learnjdk.stream;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by alex on 2016/11/19.
 */
public class Main {

    public static void main(String[] args) {
        List<Apple> apples = new ArrayList<>();
        apples.add(new Apple("red", 100));
        apples.add(new Apple("red", 220));
        apples.add(new Apple("green", 100));
        apples.add(new Apple("green", 150));
        apples.add(new Apple("green", 160));

        apples = filter2(apples);

        apples.stream().forEach(System.out::println);
    }

    static List<Apple> filter1 (List<Apple> apples) {
        FilterApples.doFilter(apples, new GreenFilter());
        FilterApples.doFilter(apples, new WeightFilter());
        return apples;
    }

    static List<Apple> filter2 (List<Apple> apples) {
        Filter filter = new GreenFilter();
        FilterApples.doFilter(apples, filter::test);
        FilterApples.doFilter(apples, new WeightFilter());
        return apples;
    }

    static List<Apple> filter3 (List<Apple> apples) {
        apples = FilterApples.doFilter(apples, apple -> "green".equals(apple.getColor()));
        apples = FilterApples.doFilter(apples, apple -> apple.getWeight() > 150);
        return apples;
    }

    static class FilterApples {
        public static List<Apple> doFilter (List<Apple> apples, Filter filter) {
            List<Apple> result = new ArrayList<>(apples.size());
            for (Apple apple : apples) {
                if (filter.test(apple)) {
                    result.add(apple);
                }
            }
            return result;
        }
    }

    static class GreenFilter implements Filter {
        @Override
        public boolean test(Apple apple) {
            return "green".equals(apple.getColor());
        }
    }

    static class WeightFilter implements Filter {
        @Override
        public boolean test(Apple apple) {
            return apple.getWeight() > 150;
        }
    }

    @FunctionalInterface
    interface Filter {
        boolean test(Apple apple);

        static boolean testColor (Apple apple) {
            return "green".equals(apple.getColor());
        }

        static boolean testWeight (Apple apple) {
            return apple.getWeight() > 150;
        }
    }
}
